import React from 'react';
import PropTypes from 'prop-types';
import MyECharts from '@components/my-echarts';
import { LEVEL_TEXT } from '@util/constants';
import _ from 'lodash';

const VulPie = props => {
  const { data, totalSites, jump } = props;
  let filterData = [];

  const colorMap = {
    fatal: ['rgba(255, 0, 0, 1)', 'rgba(255, 0, 0, 0)'],
    high: ['rgba(255,69,0, 1)', 'rgba(255,69,0, 0)'],
    middle: ['rgba(255,165,0, 1)', 'rgba(255,165,0, 0)'],
    low: ['rgba(255,255,0, 1)', 'rgba(255,255,0, 0)']
  };

  const getColor = type => {
    return {
      type: 'linear',
      x: 0,
      y: 0,
      x2: 0,
      y2: 1,
      colorStops: [
        {
          offset: 0,
          color: colorMap[type][0]
        },
        {
          offset: 1,
          color: colorMap[type][1]
        }
      ],
      global: false
    };
  };

  const getPercent = value => {
    const toExponential = ((value / totalSites) * 100).toExponential(1);
    const result = Number(toExponential);
    return result;
  };

  if (Object.keys(data).length && _.sumBy(_.valuesIn(data))) {
    filterData = [];
    _.forOwn(data, (value, key) => {
      if (value) {
        filterData.push({ value, name: LEVEL_TEXT[key], key, itemStyle: {} });
      }
    });
  } else {
    filterData = [
      { value: 0, name: '严重', key: 'fatal', itemStyle: {} },
      { value: 0, name: '高危', key: 'high', itemStyle: {} },
      { value: 0, name: '中危', key: 'middle', itemStyle: {} },
      { value: 0, name: '低危', key: 'low', itemStyle: {} }
    ];
  }

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: value => {
        return `漏洞等级： ${value.name}<br />
        影响资产数： ${value.value}<br />
        总资产占比率：${getPercent(value.value)}%`;
      }
    },
    label: {
      formatter: value => {
        return `${value.name}(${value.value})\n${getPercent(value.value)}%`;
      },
      color: '#ffffff'
    },
    series: [
      {
        type: 'pie',
        radius: ['10%', '58%'],
        minAngle: 36,
        roseType: 'radius',
        data: _.map(_.cloneDeep(filterData), item => {
          item.itemStyle['color'] = getColor(item.key);
          return item;
        })
      },
      {
        type: 'pie',
        radius: ['10%', '14%'],
        minAngle: 36,
        hoverAnimation: false,
        label: {
          show: false
        },
        data: _.map(_.cloneDeep(filterData), item => {
          item.itemStyle['color'] = colorMap[item.key][0];
          return item;
        })
      }
    ]
  };
  return <MyECharts option={option} onClick={jump} />;
};

VulPie.propTypes = {
  data: PropTypes.object,
  totalSites: PropTypes.number,
  jump: PropTypes.func
};

export default VulPie;
